package com.clb.studyproject.ui

import android.graphics.*
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.clb.studyproject.R
import java.net.URL

class CustomViewActivity : AppCompatActivity(R.layout.activity_custom_view) {

    private val picUrl = "https://img1.baidu.com/it/u=3102336817,2216289337&fm=26&fmt=auto&gp=0.jpg"
    private lateinit var img1: ImageView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        img1 = findViewById<ImageView>(R.id.img1)
        drawViewBitmap()
    }

    private fun drawViewBitmap() {
        val paint = Paint()
        paint.color = Color.RED

        Thread {
            //获取网络图片Bitmap
            val url = URL(picUrl)
            val openStream = url.openStream()
            val picBitmap = BitmapFactory.decodeStream(openStream)
            openStream.close()


            val downBitmap = Bitmap.createBitmap(300, 300, Bitmap.Config.ARGB_8888)
            val resultBitmap = Bitmap.createBitmap(300, 300, Bitmap.Config.ARGB_8888)
//            val topBitmap = Bitmap.createBitmap(300, 300, Bitmap.Config.ARGB_8888)
            val downCanvas = Canvas(downBitmap)
//            val topCanvas = Canvas(topBitmap)
            val canvas = Canvas(resultBitmap)

//            downCanvas.drawRect(Rect(0, 0, 300, 300), paint)
            downCanvas.drawCircle(150F, 150F, 150F, paint)
            canvas.drawBitmap(downBitmap, 0F, 0F, paint)

            paint.color = Color.GRAY
            val xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)
            paint.xfermode = xfermode

            canvas.drawBitmap(picBitmap, 0F, 0F, paint)

            img1.setImageBitmap(resultBitmap)
        }.start()
    }

    private fun drawViewCanvas() {
        val paint = Paint()
        paint.color = Color.RED

        val bitmap = Bitmap.createBitmap(300, 300, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bitmap)

        canvas.drawRect(Rect(0, 0, 300, 300), paint)
        paint.color = Color.GRAY
        val xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
        paint.xfermode = xfermode
        canvas.drawCircle(150F, 150F, 150F, paint)
        img1.setImageBitmap(bitmap)
    }
}
